<template>
  <a-modal
    :title="title"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="hideModal"
    :maskClosable="false"
    destroyOnClose
    width="720px"
    style="overflow: hidden;"
    :bodyStyle="{ maxHeight: '520px', overflow: 'auto' }"
  >
    <a-spin :spinning="spinning">
      <a-form-model
        :model="formData"
        :rules="rules"
        ref="myForm"
        :style="{ width: '100%' }"
        layout="horizontal"
        v-bind="{
          labelCol: { span: 4 },
          wrapperCol: { span: 20 }
        }"
        :colon="true"
        labelAlign="right"
      >
        <a-row style="height: 100%">
          <a-col :span="24">
            <a-form-model-item label="角色" prop="roleIds" v-bind="{}">
              <a-checkbox-group v-model="formData.roleIds">
                <a-checkbox v-for="(opt, idx) in roles_options" :key="idx" :value="opt.id">
                  {{ opt.roleName }}
                </a-checkbox>
              </a-checkbox-group>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { get, updRole } from '@/api/sys/user.js'
import { getAll } from '@/api/sys/role.js'
export default {
  components: {},
  props: [],
  data () {
    return {
      title: '',
      spinning: false,
      confirmLoading: false,
      visible: false,
      defaultFormData: {
        id: null,
        roleIds: []
      },
      roles_options: [],
      formData: {},
      rules: {
        roleIds: [
          {
            required: true,
            message: '角色不能为空',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    showModal (id) {
      this.formData = Object.assign({}, this.defaultFormData)
      this.visible = true
      this.roles_options = []
      getAll().then(res => {
        this.roles_options = res.data || []
      })
      if (id) {
        this.spinning = true
        this.title = '编辑'
        get({ id: id }).then(res => {
          this.formData = this.$utils.mergeObjSamePro(this.defaultFormData, res.data)
          this.spinning = false
        })
      } else {
        this.title = '添加'
      }
    },
    hideModal () {
      this.confirmLoading = false
      this.visible = false
    },
    handleOk () {
      this.confirmLoading = true
      this.$refs['myForm'].validate(valid => {
        if (!valid) {
          this.confirmLoading = false
        } else {
          if (this.formData.id) {
            updRole(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success('修改成功')
                this.hideModal()
              }
            })
          }
        }
      })
    }
  }
}
</script>
<style scoped lang="less">
/*复选框样式*/
.ant-checkbox-wrapper + .ant-checkbox-wrapper {
  margin-left: 0px;
}
</style>
